﻿using System;
using System.ComponentModel;
using System.IO;
using AI3SaveEditor.AI3Files;

namespace AI3SaveEditor
{
    public abstract class AI3File
    {
        [Category("系统"), DisplayName("文件路径"), Description("文件路径")]
        public string FileName
        {
            get
            {
                return this.file.FullName;
            }
        }

        public AI3File(string fileName)
        {
            this.file = new FileInfo(fileName);
        }

        protected FileInfo file;
        protected byte[] buffer;
        public abstract void Load();
        protected abstract void DecryptFileContent(byte[] fileContent);

        protected void SetInt32ToBuffer(int value, int start)
        {
            IllusionUtils.SetInt32(value, buffer, start);
        }

        public static AI3File Load(string filePath)
        {
            if (string.IsNullOrEmpty(filePath))
                throw new ApplicationException("文件路径不能为空");
            if (filePath.EndsWith("js3cmi", StringComparison.CurrentCultureIgnoreCase))
                return new Js3cmiFile(filePath);
            else if (filePath.EndsWith("js3csi", StringComparison.CurrentCultureIgnoreCase))
                return new Js3csiFile(filePath);
            else if (filePath.EndsWith("js3fmi", StringComparison.CurrentCultureIgnoreCase))
                return new Js3fmiFile(filePath);
            else if (filePath.EndsWith("js3fsi", StringComparison.CurrentCultureIgnoreCase))
                return new Js3fsiFile(filePath);
            throw new ApplicationException(string.Format("不支持的文件格式 {0}", Path.GetExtension(filePath)));
        }

        public virtual void Save()
        {
            byte[] fileContent = IllusionUtils.CloneBytes(buffer, 0);
            DecryptFileContent(fileContent);
            File.WriteAllBytes(this.file.FullName, fileContent);
            this.file.Refresh();
        }

        public DateTime LastWriteTime
        {
            get
            {
                return file.LastWriteTime;
            }
        }
    }
}
